#coding:utf-8
import wsgiref.handlers
import os
from functools import wraps
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.api import users
import methods,logging
from django.utils import simplejson

class AdminControl(webapp.RequestHandler):
    def render(self,template_file,template_value):
        path=os.path.join(os.path.dirname(__file__),template_file)
        
        # add user information to template_value
        template_value["user_greeting"] = methods.getUserGreeting("/list/")

        self.response.out.write(template.render(path, template_value))
    
    def returnjson(self,dit):
        self.response.headers['Content-Type'] = "application/json"
        self.response.out.write(simplejson.dumps(dit))
        
def requires_admin(method):
    @wraps(method)
    def wrapper(self, *args, **kwargs):
        if not users.is_current_user_admin():
            self.redirect("/")
        else:
            return method(self, *args, **kwargs)
    return wrapper


class Admin_Upload(AdminControl):
    @requires_admin
    def get(self):
        self.redirect('/manage/')

    @requires_admin
    def post(self):
        bf=self.request.get("file")
        if not bf:
            return self.redirect('/manage/')
        name = self.request.body_file.vars['file'].filename
        mime = self.request.body_file.vars['file'].headers['content-type']
        file = methods.addFile( name, mime, bf)
        
        # show result
        msg = ""
        if not file:
            msg = "Failed to upload file '%s'!" %(name)
        else:
            msg = "File '%s' (id:%s) has been uploaded successfully!" %(name, file.id )
        	
        template_value = {"upload_message": msg}
        self.render('views/admin.html', template_value)


class Admin_Delete(AdminControl):
    @requires_admin
    def get(self,id):
        self.redirect('/manage/')

    @requires_admin
    def post(self):
        file_id = self.request.get("file_id")
        msg = ""
        if not file_id:
            msg = "Please input file_id..."
        else:
            result = methods.delFileByid(file_id)
            msg = "Operation Result: %s " %(result)

        # show result
        template_value = {"delete_message": msg}
        self.render('views/admin.html', template_value)

class Admin_Portal(AdminControl):
    @requires_admin
    def get(self):
        self.render('views/admin.html', {})

    @requires_admin
    def post(self):
        pass
	
def main():
    application = webapp.WSGIApplication(
                                       [(r'/manage/upload/', Admin_Upload),
                                        (r'/manage/delete/', Admin_Delete),
                                        (r'/manage/', Admin_Portal),
                                       ], debug=True)
    wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
    main()
